package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    // 创建显示等待对象
    public static WebDriverWait wait = null;

    public Utils(String url){
        // 创建 driver
        driver = createDriver();
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, Duration.ofSeconds(20));
        // 访问 url
        driver.get(url);
    }

    /**
     * 创建 driver 驱动对象
     */
    public static WebDriver createDriver(){
        if(null == driver){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            // 允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            driver = new ChromeDriver(options);
            // 关键：设置全局隐式等待（所有元素查找都会等待最多30秒）
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
        }
        return driver;
    }

    /**
     * 屏幕截图
     * 目录
     * ./src/test/java/images/
     *                       /2025-10-06/
     *                                  /test01_09372010.png
     *                                  /test01_09372011.png
     *                       /2025-10-07/
     *                                  /test01_19372010.png
     *                                  /test01_19372011.png
     */
    public void ScreenShot(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/java/images/" + dirTime + "/" + str + "_" + fileTime + ".png";

        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(fileName));
    }
}
